package com.pony.iphone.controller;

import com.pony.iphone.dto.BaseResponse;
import com.pony.iphone.dto.QWenResponse;
import com.pony.iphone.dto.QuestionAnswerDto;
import com.pony.iphone.dto.UsageStats;
import com.pony.iphone.exception.QWenServiceException;
import com.pony.iphone.service.impl.QWenChatService;
import com.pony.iphone.service.impl.QWenHistoryService;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/ai")
public class QWenController {

    @Autowired
    private QWenChatService qwenChatService;

    @Autowired
    private QWenHistoryService historyService;

    @Autowired
    private OpenAiService openAiService;

    @Value("${app.ai.timeout:300000}")
    private long timeout;

    @GetMapping("/network-check")
    public ResponseEntity<BaseResponse<Map<String, Object>>> networkCheck() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查是否能访问DeepSeek API
            URL url = new URL("https://api.deepseek.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.setRequestMethod("HEAD");

            int responseCode = connection.getResponseCode();
            result.put("deepseek_api_accessible", responseCode == 200);
            result.put("response_code", responseCode);
            result.put("api_endpoint", "https://api.deepseek.com");

        } catch (Exception e) {
            result.put("deepseek_api_accessible", false);
            result.put("error", e.getMessage());
        }

        // 检查本地网络信息
        result.put("local_timestamp", System.currentTimeMillis());
        result.put("java_version", System.getProperty("java.version"));
        result.put("os_name", System.getProperty("os.name"));

        // 从配置中获取超时设置
        try {
            result.put("configured_timeout", timeout + "ms"); // 如果timeout在类中定义了
        } catch (Exception e) {
            result.put("configured_timeout", "未配置");
        }

        return ResponseEntity.ok(BaseResponse.success("网络检查结果", result));
    }

    @GetMapping("/openai-test")
    public ResponseEntity<BaseResponse<String>> testOpenAIConnection() {
        try {
            // 简单的测试请求
            List<ChatMessage> messages = new ArrayList<>();
            messages.add(new ChatMessage(ChatMessageRole.USER.value(), "Say 'hello'"));

            ChatCompletionRequest request = ChatCompletionRequest.builder()
                    .model("deepseek-chat")
                    .messages(messages)
                    .maxTokens(10)
                    .build();

            // 设置短超时进行连接测试
            ChatCompletionResult result = openAiService.createChatCompletion(request);
            return ResponseEntity.ok(BaseResponse.success("连接测试成功: " + result.getChoices().get(0).getMessage().getContent()));

        } catch (Exception e) {
            log.error("DeepSeek连接测试失败", e);
            return ResponseEntity.status(500)
                    .body(BaseResponse.error("连接测试失败: " + e.getMessage()));
        }
    }

    @GetMapping("/openai-info")
    public ResponseEntity<BaseResponse<Map<String, Object>>> getOpenAiInfo() {
        try {
            Map<String, Object> info = new HashMap<>();

            // 使用反射获取OpenAiService的内部信息
            java.lang.reflect.Field[] fields = openAiService.getClass().getDeclaredFields();
            for (java.lang.reflect.Field field : fields) {
                try {
                    field.setAccessible(true);
                    Object value = field.get(openAiService);
                    info.put(field.getName(), value != null ? value.toString() : "null");
                } catch (Exception e) {
                    info.put(field.getName(), "无法访问: " + e.getMessage());
                }
            }

            return ResponseEntity.ok(BaseResponse.success("OpenAiService信息", info));
        } catch (Exception e) {
            return ResponseEntity.status(500)
                    .body(BaseResponse.error("获取信息失败: " + e.getMessage()));
        }
    }

    @PostMapping("/chat/question")
    public ResponseEntity<BaseResponse<QWenResponse>> chat(
            @Valid @RequestBody QuestionAnswerDto request) {
        try {
            // 对于简单的是非问题，可以直接逻辑判断，避免调用AI
            String directAnswer = tryDirectAnswer(request);
            if (directAnswer != null) {
                QWenResponse quickResponse = buildQuickResponse(directAnswer);
                return ResponseEntity.ok(BaseResponse.success("直接逻辑判断", quickResponse));
            }

            // 直接调用 Service 方法
            QWenResponse response = qwenChatService.chatWithHistory(request);

            log.info("问题: {}, 最终答案: {}", request.getQuestion(), response.getAnswer());

            return ResponseEntity.ok(BaseResponse.success(response));

        } catch (QWenServiceException e) {
            log.error("千问服务异常: {}", e.getMessage());
            return ResponseEntity.badRequest().body(BaseResponse.error(e.getMessage()));
        } catch (Exception e) {
            log.error("系统异常: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(BaseResponse.error("系统内部错误"));
        }
    }

    /**
     * 尝试直接逻辑判断
     */
    private String tryDirectAnswer(QuestionAnswerDto request) {
        String question = request.getQuestion().toLowerCase();
        List<String> answers = request.getAnswerList();

        // 简单的逻辑判断
        if (answers.size() == 2 && answers.contains("Yes") && answers.contains("No")) {
            if (question.contains("do you want") || question.contains("would you like")) {
                return "Yes";
            }
            if (question.contains("exit") || question.contains("leave") || question.contains("quit")) {
                return "No";
            }
        }
        return null;
    }

    /**
     * 构建快速响应
     */
    private QWenResponse buildQuickResponse(String answer) {
        return QWenResponse.builder()
                .answer(answer)
                .tokensUsed(0L)
                .responseTime(0L)
                .status("SUCCESS")
                .model("direct-logic")
                .build();
    }

    /**
     * 获取历史统计
     */
    @GetMapping("/history/stats")
    public ResponseEntity<BaseResponse<Object>> getHistoryStats() {
        try {
            Object stats = historyService.getHistoryStats();
            return ResponseEntity.ok(BaseResponse.success(stats));
        } catch (Exception e) {
            log.error("获取历史统计失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(BaseResponse.error("获取历史统计失败"));
        }
    }

    /**
     * 导出历史数据
     */
    @GetMapping("/history/export")
    public ResponseEntity<Resource> exportHistory() {
        try {
            File exportFile = historyService.exportHistory();

            Path path = Paths.get(exportFile.getAbsolutePath());
            org.springframework.core.io.Resource resource = new org.springframework.core.io.InputStreamResource(Files.newInputStream(path));

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + exportFile.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);

        } catch (Exception e) {
            log.error("导出历史数据失败: {}", e.getMessage());
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<BaseResponse<String>> healthCheck() {
        try {
            return ResponseEntity.ok(BaseResponse.success("服务运行正常"));
        } catch (Exception e) {
            log.error("健康检查失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(BaseResponse.error("服务异常"));
        }
    }

    /**
     * 全局异常处理
     */
    @ExceptionHandler(QWenServiceException.class)
    public ResponseEntity<BaseResponse<String>> handleQWenServiceException(QWenServiceException e) {
        log.error("千问服务异常: {}", e.getMessage());
        return ResponseEntity.badRequest().body(BaseResponse.error(e.getMessage()));
    }

    /**
     * 全局异常处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<BaseResponse<String>> handleException(Exception e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ResponseEntity.status(500)
                .body(BaseResponse.error("系统内部错误: " + e.getMessage()));
    }
}